package cn.ihoway.room;

import cn.ihoway.annotation.Processor;
import cn.ihoway.common.CommonProcessor;
import cn.ihoway.entity.Allocation;
import cn.ihoway.entity.Room;
import cn.ihoway.redis.AllocationRedis;
import cn.ihoway.redis.RoomRedis;
import cn.ihoway.room.io.RoomJoinInput;
import cn.ihoway.room.io.RoomJoinOutput;
import cn.ihoway.socket.GameSessionManager;
import cn.ihoway.type.StatusCode;
import cn.ihoway.util.HowayLog;
import cn.ihoway.util.HowayMessage;
import cn.ihoway.util.HowayWsResult;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 加入房间
 */
@Processor(name = "RoomJoinProcessor")
public class RoomJoinProcessor  extends CommonProcessor<RoomJoinInput, RoomJoinOutput> {
    private final HowayLog logger = new HowayLog(RoomJoinProcessor.class);
    private final RoomRedis roomRedis = new RoomRedis();
    private final AllocationRedis allocationRedis = new AllocationRedis();

    @Override
    protected StatusCode dataCheck(RoomJoinInput input){
        return StatusCode.SUCCESS;
    }
    
    @Override
    protected HowayWsResult process(RoomJoinInput input, RoomJoinOutput output) throws IOException {
        Room room = roomRedis.get(input.inChomm.roomId);
        if(room == null){
            return HowayWsResult.createFailResult(StatusCode.ROOM_NOT_FOUND,output);
        }
        Integer maxNum = room.getMaxNum();
        Integer num = room.getCurrentNum();
        if(maxNum.equals(num)){
            //房间满员,禁止加入
            return HowayWsResult.createFailResult(StatusCode.ROOM_FULL,output);
        }
        room.setCurrentNum(num+1);
        room.setStatus(0);
        //玩家加入房间
        Allocation allocationPre = allocationRedis.getBySessionId(input.inChomm.sessionId);
        if(allocationPre != null){
            //用户存在，禁止重复加入
            return HowayWsResult.createFailResult(StatusCode.DUPLICATE_JOIN,output);
        }
        Allocation allocation = new Allocation();
        allocation.setPlayerId(String.valueOf(num+1));
        allocation.setRoomId(room.getId());
        allocation.setSessionId(input.inChomm.sessionId);
        allocation.setIsAlive(1);
        allocation.setIsOnline(1);
        allocation.setPlayerType(1);
        allocation.setIsReady(0);

        roomRedis.put(room.getId(),room);
        allocationRedis.update(allocation);
        logger.info("玩家" + input.inChomm.sessionId + "加入房间" + room.getId() + "成功");
        //广播：推送消息改成JSON格式的
        ArrayList<WebSocketSession> sessions = GameSessionManager.getFromRoom(input.inChomm.roomId);
        for(WebSocketSession socketSession: sessions){
            HowayMessage message = new HowayMessage("用户" + input.inChomm.sessionId + "加入房间");
            socketSession.sendMessage(new TextMessage(message.toString()));
        }
        return HowayWsResult.createSuccessResult(output);
    }
}